package cn.lbaicai.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.lbaicai.entity.User;
import cn.lbaicai.service.UserService;
import cn.lbaicai.utils.PasswordHelper;

@Controller
public class RegisterController {
	@Autowired
	private UserService userService;
	@RequestMapping(value="/register",method=RequestMethod.GET)
	public String register(){
		return "register";
	}
	@RequestMapping(value="/register",method=RequestMethod.POST)
	@ResponseBody
	public Object registers(HttpServletRequest request){
		int Code =201;
		String Msg;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String username = request.getParameter("username");
		String phone = request.getParameter("phone");
		String password = request.getParameter("password");
		String nickname = request.getParameter("nickname");
		String agreement = request.getParameter("agreement");
		User user = new User();
		user.setUsername(username);
		if(agreement.equals("no")){
			user.setAgreement(true);
		}else{
			user.setAgreement(false);
		}
		user.setPhone(phone);
		user.setNick(nickname); 
		user.setPassword(password);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		user.setCreated(sdf.format(new Date()));
		User users = userService.selectByUser(user);
		if(users==null){
			PasswordHelper pHelper = new PasswordHelper();
			pHelper.encryptPassword(user);
			int iFlag =  userService.insertSelective(user);
			if(iFlag>0){
				Code=200;
				Msg="注册成功";
			}else{
				Msg="注册失败";
			}
		}else{
			Msg="用户已存在";
		}
  		resultMap.put("code",Code);
  		resultMap.put("msg",Msg);
		return JSON.toJSON(resultMap);
	}
}
